const Service = require('egg').Service;
const crypto = require('crypto');

// 基于crypto封装sha1加密
function sha1(str) {
    return crypto.createHash('sha1').update(str, 'utf-8').digest('hex');
}

function checkSignature(token, opts) {
    let { signature, timestamp, nonce } = opts;
    // 添加到数组中
    let arr = [token, timestamp, nonce];
    // 排序
    arr.sort();
    // 拼接成一个字符串
    let temStr = arr.join('');
    // 加密
    temStr = sha1(temStr);
    console.log(signature, '/r/n', temStr)
    if (signature === temStr) {
        return true;
    } else {
        return false;
    }
}

class WxService extends Service {
    async verify() {
        const { ctx, app } = this;
        if (checkSignature(app.config.weChat.token, ctx.query)) {
            return ctx.query.echostr;
        } else {
            return false;
        }
    }
}

module.exports = WxService;